package com.flyan.danmuhunter.bilibili.data.resp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flyan.danmuhunter.bilibili.config.Config;
import com.flyan.danmuhunter.bilibili.data.Header;
import com.flyan.danmuhunter.common.utils.ByteArrayUtil;
import com.flyan.danmuhunter.common.utils.ZLibUtil;
import lombok.Getter;
import lombok.ToString;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.flyan.danmuhunter.common.utils.Helper._not;
import static com.flyan.danmuhunter.common.utils.Helper._str_not_black;

/**
 * 直播服务器返回的结果
 *
 * @author flyan
 * @version 1.0
 * @date 2022/6/7
 */
@Getter
public class LiveResult {

    private final Header header;
    private String body = "";
    private List<JSONObject> cmdData = null;

    public LiveResult(ByteBuffer resultBytes) {
        this.header = new Header(resultBytes);
        byte[] data = ByteArrayUtil.slice(resultBytes.array(), this.header.getHeaderLength(), resultBytes.array().length);
        assert data != null;

        /* 根据操作不同处理结果 */
        switch (this.header.getOp().getOpType()) {
            /* 人气值 */
            case POPULAR_VAL:
                this.body = String.valueOf(resultBytes.getInt());
                break;

            /* 具体命令 */
            case CMD:
                String temp;
                this.cmdData = new ArrayList<>();
                if(_not(Config.PROTOCOL_VERSION_HAS_ENCODE.get(this.header.getProtocolVersion()))) {
                    temp = new String(data, StandardCharsets.UTF_8);
                } else {
                    temp = ZLibUtil.decompressStr(data);
                }
                /* 同一条消息中可能存在多条信息，用正则筛出来 */
                this.body = temp;
                if(_str_not_black(temp)) {
                    Arrays.stream(temp.split("[\\x00-\\x1f]+")).forEach(x -> {
                        try {
                            if(_str_not_black(x)) {
                                this.cmdData.add(JSONObject.parseObject(x));
                            }
                        } catch (Exception e) {
                            /* 忽略非JSON字符串，通常情况下为分隔符 */
                        }
                    });
//                    this.body = JSON.toJSONString(this.cmdData);
                }
                break;

            default:
                break;
        }
    }

    @Override
    public String toString() {
        return "LiveResult{" +
                "header=" + header +
                ", body='" + body + '\'' +
                '}';
    }
}
